package cn.com.cetccst.illegalconnection.demo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import java.util.ArrayList;
import java.util.List;

import cn.com.cetccst.illegalconnection.Address;
import cn.com.cetccst.illegalconnection.IllegalConnectionEngine;

public class ConfigDlg extends AlertDialog.Builder {
    private View view;

    public static void show(Context context, Callback callback) {

        new ConfigDlg(context, callback).show();
    }

    public ConfigDlg(@NonNull Context context, Callback callback) {
        super(context);
        view = LayoutInflater.from(context).inflate(R.layout.address_input, null, false);
        Address[] params = IllegalConnectionEngine.getInstance().getParams();
        if (params != null) {
            if (params.length > 0) {
                ((TextView) view.findViewById(R.id.address1)).setText(params[0].getIp());
            }
            if (params.length > 1) {
                ((TextView) view.findViewById(R.id.address2)).setText(params[1].getIp());
            }
        }
        setView(view)
                .setPositiveButton("确定", (dialog, which) -> {
                    String address1 = ((TextView) view.findViewById(R.id.address1)).getText().toString();
                    String address2 = ((TextView) view.findViewById(R.id.address2)).getText().toString();
                    List<Address> addressList = new ArrayList<>();
                    if (!address1.isEmpty()) {
                        addressList.add(new Address("addr1", address1, "80", "note1"));
                    }
                    if (!address2.isEmpty()) {
                        addressList.add(new Address("addr2", address2, "80", "note2"));
                    }
                    callback.handleAddressList(addressList);
                })
                .setNegativeButton("清空", (dialogInterface, i) -> callback.handleAddressList(null));
    }

    public interface Callback {
        void handleAddressList(List<Address> addressList);
    }
}
